package com.xgr.wonderful.utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;

import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;

public class HXUtils {
	private static final String TAG ="HXUtils" ;

	// 在环信的服务器上注册账号,取消使用
	public static void EMRegister(final String username, final String passwd) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					EMChatManager.getInstance().createAccountOnServer(username,
							passwd);
					LogUtils.i(TAG,"register with HX server successful");
				} catch (EaseMobException e) {
					// TODO: handle exception
					int errorCode = e.getErrorCode();
					if (errorCode == EMError.NONETWORK_ERROR) {
						LogUtils.i(TAG,"register with HX server failure with network error");
					} else if (errorCode == EMError.USER_ALREADY_EXISTS) {
						LogUtils.i(TAG,"register with HX server failure with duplicate user");
					} else if (errorCode == EMError.UNAUTHORIZED) {
						LogUtils.i(TAG,"register with HX server failure with unauthorized");
					} else {
						LogUtils.i(TAG,"register with HX server failure with unkown issue");
					}
				}
			}
		}).start();
	}

	// 登录环信的服务器
	public static void EMLogin(String username, String passwd) {
		EMChatManager.getInstance().login(username, passwd, new EMCallBack() {

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				HXUtils.EMLoadConversations();
			}

			@Override
			public void onProgress(int arg0, String arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stub
				LogUtils.i(TAG, "login HX server failure");
			}
		});
	}

	public static void EMLoadConversations() {
		try {
			EMChatManager.getInstance().loadAllConversations();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	/**
	 * 新消息接收的广播 
	 * @param activity
	 * @param broadcastReceiver
	 * @param priority
	 */
	public static void EMRegisterReceiver(Activity activity,
			BroadcastReceiver broadcastReceiver, int priority) {
		IntentFilter intentFilter = new IntentFilter(EMChatManager
				.getInstance().getNewMessageBroadcastAction());
		intentFilter.setPriority(priority);
		activity.registerReceiver(broadcastReceiver, intentFilter);
	}

}
